/**
 * PyCron Web界面JavaScript
 */

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    initTooltips();

    // 初始化表单验证
    initFormValidation();

    // 初始化自动刷新（可选）
    // initAutoRefresh();
});

/**
 * 初始化工具提示
 */
function initTooltips() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

/**
 * 初始化表单验证
 */
function initFormValidation() {
    const forms = document.querySelectorAll('.needs-validation');

    Array.prototype.slice.call(forms).forEach(function(form) {
        form.addEventListener('submit', function(event) {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }

            form.classList.add('was-validated');
        }, false);
    });
}

/**
 * 显示加载状态
 */
function showLoading(element) {
    element.classList.add('loading');
}

/**
 * 隐藏加载状态
 */
function hideLoading(element) {
    element.classList.remove('loading');
}

/**
 * 显示提示消息
 */
function showMessage(message, type = 'info') {
    const alertClass = `alert-${type}`;
    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;

    const container = document.querySelector('.container');
    if (container) {
        container.insertAdjacentHTML('afterbegin', alertHtml);
    }
}

/**
 * 确认对话框
 */
function confirmAction(message, callback) {
    if (window.confirm(message)) {
        callback();
    }
}

/**
 * 格式化日期时间
 */
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '从未';

    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

/**
 * 格式化相对时间
 */
function formatRelativeTime(dateTimeStr) {
    if (!dateTimeStr) return '从未';

    const now = new Date();
    const date = new Date(dateTimeStr);
    const diffMs = now - date;
    const diffSeconds = Math.floor(diffMs / 1000);
    const diffMinutes = Math.floor(diffSeconds / 60);
    const diffHours = Math.floor(diffMinutes / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffSeconds < 60) {
        return `${diffSeconds}秒前`;
    } else if (diffMinutes < 60) {
        return `${diffMinutes}分钟前`;
    } else if (diffHours < 24) {
        return `${diffHours}小时前`;
    } else if (diffDays < 7) {
        return `${diffDays}天前`;
    } else {
        return formatDateTime(dateTimeStr);
    }
}

/**
 * Cron表达式验证
 */
function validateCronExpression(expression) {
    // 简单的客户端验证
    const parts = expression.trim().split(/\s+/);
    if (parts.length !== 6) {
        return false;
    }

    // 检查每个部分是否为有效值
    const ranges = [
        [0, 59], // 秒
        [0, 59], // 分
        [0, 23], // 时
        [1, 31], // 日
        [1, 12], // 月
        [0, 6]  // 周
    ];

    for (let i = 0; i < parts.length; i++) {
        const part = parts[i];
        if (part === '*' || part === '?') {
            continue;
        }

        // 检查范围
        if (part.includes('-')) {
            const [start, end] = part.split('-').map(Number);
            if (start < ranges[i][0] || end > ranges[i][1] || start > end) {
                return false;
            }
        } else if (part.includes(',')) {
            const values = part.split(',').map(Number);
            for (const value of values) {
                if (value < ranges[i][0] || value > ranges[i][1]) {
                    return false;
                }
            }
        } else if (part.includes('/')) {
            const value = Number(part.split('/')[0]);
            if (value < ranges[i][0] || value > ranges[i][1]) {
                return false;
            }
        } else {
            const value = Number(part);
            if (isNaN(value) || value < ranges[i][0] || value > ranges[i][1]) {
                return false;
            }
        }
    }

    return true;
}

/**
 * 实时Cron表达式验证
 */
function initCronValidation() {
    const cronInput = document.getElementById('cron_expression');
    const feedback = document.createElement('div');

    if (cronInput) {
        feedback.className = 'form-text';
        cronInput.parentNode.appendChild(feedback);

        cronInput.addEventListener('input', function() {
            const expression = this.value.trim();
            if (expression) {
                if (validateCronExpression(expression)) {
                    feedback.innerHTML = '<small class="text-success"><i class="fas fa-check-circle me-1"></i>Cron表达式格式正确</small>';
                    this.classList.remove('is-invalid');
                    this.classList.add('is-valid');
                } else {
                    feedback.innerHTML = '<small class="text-danger"><i class="fas fa-times-circle me-1"></i>Cron表达式格式错误</small>';
                    this.classList.remove('is-valid');
                    this.classList.add('is-invalid');
                }
            } else {
                feedback.innerHTML = '';
                this.classList.remove('is-valid', 'is-invalid');
            }
        });
    }
}

/**
 * 复制到剪贴板
 */
function copyToClipboard(text) {
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(function() {
            showMessage('已复制到剪贴板', 'success');
        }).catch(function(err) {
            console.error('复制失败:', err);
            fallbackCopyToClipboard(text);
        });
    } else {
        fallbackCopyToClipboard(text);
    }
}

/**
 * 降级复制方法
 */
function fallbackCopyToClipboard(text) {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    textArea.style.top = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
        document.execCommand('copy');
        showMessage('已复制到剪贴板', 'success');
    } catch (err) {
        console.error('复制失败:', err);
        showMessage('复制失败，请手动复制', 'error');
    }

    document.body.removeChild(textArea);
}

/**
 * 自动刷新功能（可选）
 */
function initAutoRefresh() {
    let refreshInterval;

    // 添加自动刷新控制
    const refreshControl = document.createElement('div');
    refreshControl.className = 'd-flex align-items-center mb-3';
    refreshControl.innerHTML = `
        <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" id="autoRefresh">
            <label class="form-check-label" for="autoRefresh">
                <small class="text-muted">自动刷新 (30秒)</small>
            </label>
        </div>
    `;

    const container = document.querySelector('.container');
    if (container) {
        const firstChild = container.firstElementChild;
        container.insertBefore(refreshControl, firstChild);
    }

    // 自动刷新切换
    const autoRefreshCheckbox = document.getElementById('autoRefresh');
    if (autoRefreshCheckbox) {
        autoRefreshCheckbox.addEventListener('change', function() {
            if (this.checked) {
                refreshInterval = setInterval(function() {
                    location.reload();
                }, 30000); // 30秒刷新一次
                showMessage('已启用自动刷新', 'info');
            } else {
                if (refreshInterval) {
                    clearInterval(refreshInterval);
                }
                showMessage('已禁用自动刷新', 'info');
            }
        });
    }
}

/**
 * 页面离开确认
 */
function confirmPageLeave() {
    let hasUnsavedChanges = false;

    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        const inputs = form.querySelectorAll('input, textarea, select');

        inputs.forEach(input => {
            // 保存原始值
            input.dataset.originalValue = input.value;

            // 监听输入变化
            input.addEventListener('input', function() {
                if (this.value !== this.dataset.originalValue) {
                    hasUnsavedChanges = true;
                }
            });

            input.addEventListener('change', function() {
                if (this.value !== this.dataset.originalValue) {
                    hasUnsavedChanges = true;
                }
            });
        });

        // 监听表单提交，提交时清除未保存标记
        form.addEventListener('submit', function() {
            hasUnsavedChanges = false;
        });

        // 监听取消按钮点击
        const cancelLinks = form.querySelectorAll('a[href*="index"]');
        cancelLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                if (hasUnsavedChanges) {
                    const confirmed = confirm('您有未保存的更改，确定要离开吗？');
                    if (!confirmed) {
                        e.preventDefault();
                        return false;
                    }
                }
                hasUnsavedChanges = false; // 清除标记
            });
        });
    });

    // 监听页面卸载
    window.addEventListener('beforeunload', function(e) {
        if (hasUnsavedChanges) {
            e.preventDefault();
            e.returnValue = '您有未保存的更改，确定要离开吗？';
            return e.returnValue;
        }
    });

    // 监听链接点击
    document.addEventListener('click', function(e) {
        const link = e.target.closest('a');
        if (link && hasUnsavedChanges) {
            // 排除某些链接（如取消按钮、Cron帮助链接等）
            const href = link.getAttribute('href');
            if (href && (
                href.includes('#') ||
                href.includes('cron_examples') ||
                href.includes('javascript:') ||
                link.getAttribute('target') === '_blank' ||
                link.classList.contains('btn-outline-secondary')
            )) {
                return; // 不阻止这些链接
            }

            const confirmed = confirm('您有未保存的更改，确定要离开吗？');
            if (!confirmed) {
                e.preventDefault();
                return false;
            }
        }
    });
}

/**
 * 键盘快捷键
 */
function initKeyboardShortcuts() {
    document.addEventListener('keydown', function(e) {
        // Ctrl+Enter 提交表单
        if (e.ctrlKey && e.key === 'Enter') {
            const submitBtn = document.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.click();
            }
        }

        // Escape 取消/返回
        if (e.key === 'Escape') {
            const cancelBtn = document.querySelector('a[href*="index"]');
            if (cancelBtn) {
                cancelBtn.click();
            }
        }
    });
}

/**
 * 初始化所有增强功能
 */
function initEnhancedFeatures() {
    initCronValidation();
    confirmPageLeave();
    initKeyboardShortcuts();
}

// 当页面完全加载后初始化增强功能
window.addEventListener('load', initEnhancedFeatures);
